<template>
  <el-button type="primary" @click="BackSubmit()">返回列表</el-button>
  <el-form :model="tableData" label-width="auto" style="max-width: 1600px">


    <el-form-item>
      <img v-if="imageUrl" :src="imageUrl" class="avatar" style="max-width: 400px; max-height: 400px;"
        alt="Preview Image" />
      <div style="float: right; margin-top: 10px;margin-left: 50px;">
        <span style="font-size: 28px;color: black;font-weight: 1000;">
          {{ ShopName }}
        </span>
        <br />
        <span style="font-size: 16px;color: black;">
          生产批次:
          {{ tableData.rabit_Batch
          }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          保质期:
          {{ tableData.rabit_Shelflife }}
        </span>
        <br />
        <span style="font-size: 16px;color: black;">
          生产许可证:
          {{ tableData.rabit_Shencan }}&nbsp;&nbsp;&nbsp;&nbsp;
          生产厂商:
          {{ tableData.rabit_Company }}
        </span>
        <br />
        <span style="font-size: 16px;color: black;font-weight: 1000">
          产品检验报告:
        </span>
        <br />
        <span style="font-size: 16px;color: black;">
          <!-- 图片预览地址 -->
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl"/>
          </el-dialog>
          <!-- 上传图片以','分开存储字符串 -->
          <el-upload class="avatar-uploader" v-model:file-list="fileList" action="http://localhost:5094/api/Fileall/Fileup"
      :on-success="handleAvatarSuccess"      list-type="picture-card" :before-upload="beforeAvatarUpload"
              :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :limit="9">

            <el-icon class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>

        </span>
      </div>
    </el-form-item>
  </el-form>

  <el-tabs v-model="activeName" @tab-click="handleTabClick">
    <el-tab-pane label="养殖信息" name="FarmingsAll"></el-tab-pane>
    <el-tab-pane label="屠宰信息" name="SlaughtsAll"></el-tab-pane>
    <el-tab-pane label="深加工信息" name="ProcessiingsAll"></el-tab-pane>
    <router-view />
  </el-tabs>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
const router = useRouter()//路由传递地址
const route = useRoute()
const activeName = ref(route.name || 'FarmingsAll')
//标签页触发事件的方法
const handleTabClick = (tab: any) => {
  router.push({
    path: `/${tab.paneName}`,
    query: {
      Batch: location.search.split("=")[1]
    } // 保持原有参数，比如id
  })
}
const imageUrl = ref("")
const ShopName = ref("")
const options = ref([
  { shop_Id: 0, shop_Name: "请选择" },
])
//溯源列表
const tableData = ref({
  rabit_Id: 0,
  sId: 0,
  rabit_Batch: location.search.split("=")[1],
  rabit_Shelflife: 0,
  rabit_Shencan: "",
  rabit_Company: "",
  rabit_Infomation: "",
  rabit_TitleImg: "",
  rabit_IsDel: false,
  creater: "",
  createTime: "",
  updater: "",
  updateTime: "",
  rabit_CheckImg: ""
})//钩子函数
onMounted(() => {

//获取内容信息
    ContentEdit()
  if (route.path === '/ShowRabitsDetail') {
    router.replace({
      path: '/FarmingsAll',
      query: {
        Batch: location.search.split("=")[1]
      }
    })
  }
  activeName.value = route.path.split('/').pop() || 'FarmingsAll'
})
//循环获取对应id的商品名称
const ShowShop = () => {
  axios.get('http://localhost:5094/api/RabitsAll/ShowShop').then(res => {
    options.value = res.data.data
    res.data.data.forEach((element: any) => {
      if (element.shop_Id == tableData.value.sId) {
        ShopName.value = element.shop_Name
      }
    })
  })
}
//获取溯源数据
const ContentEdit = () => {
  axios.get("http://localhost:5094/api/RabitsAll/FirstRabits", {
    params: {
      Batch: location.search.split("=")[1]
    }
  }).then(res => {
    tableData.value = res.data.data
    imageUrl.value = tableData.value.rabit_TitleImg
      ShowShop()//循环获取对应id的商品名称
    // 初始化图片列表
    initImageList()
  })
}
//返回列表方法
const BackSubmit = () => {
  window.location.href = "/ShowRabits"
}
//图片验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // 再次检查图片数量限制（双重保险）
  const currentImageCount = tableData.value.rabit_CheckImg ? 
    tableData.value.rabit_CheckImg.split(',').filter(url => url.trim() !== '').length : 0
  if (currentImageCount >= 9) {
    ElMessage.error('最多只能上传9张图片')
    return
  }
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/webp') {
    ElMessage.error('只能传jpg类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M')
    return false
  }
  return true
}
//图片数据
const fileList = ref<UploadUserFile[]>([])

// 初始化图片列表
const initImageList = () => {
  if (tableData.value.rabit_CheckImg && tableData.value.rabit_CheckImg !== '') {
    const imageUrls = tableData.value.rabit_CheckImg.split(',').filter(url => url.trim() !== '')
    fileList.value = imageUrls.map((url, index) => ({
      name: `image_${index + 1}.jpg`,
      url: url.trim()
    }))
  } else {
    fileList.value = []
  }
}
// 添加新上传的图片到数组，并更新到数据库中
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
      // 再次检查图片数量限制（双重保险）
  const currentImageCount = tableData.value.rabit_CheckImg ? 
    tableData.value.rabit_CheckImg.split(',').filter(url => url.trim() !== '').length : 0
  if (currentImageCount >= 9) {
    ElMessage.error('最多只能上传9张图片')
    return
  }
  const newImageUrl = response.data
  if (tableData.value.rabit_CheckImg && tableData.value.rabit_CheckImg !== '') {
    tableData.value.rabit_CheckImg += ',' + newImageUrl
  } else {
    tableData.value.rabit_CheckImg = newImageUrl
  }

  // 保存到数据库
  saveImagesToDatabase()
  
  ElMessage.success('图片上传成功')
}

// 保存图片数组到数据库
const saveImagesToDatabase = () => {
  axios.get('http://localhost:5094/api/RabitsAll/UpdateCheckImages', {
    params: {
      Batch: tableData.value.rabit_Batch,
      CheckImages: tableData.value.rabit_CheckImg
    }
  }).then(res => {
      ElMessage.success('图片保存成功')
  }).catch(err => {
    ElMessage.error('图片保存失败: ' + err.message)
  })
}

//图片地址
const dialogImageUrl = ref('')
//图片弹窗
const dialogVisible = ref(false)
//图片删除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // 从数组中移除对应的图片URL
  const imageUrls = tableData.value.rabit_CheckImg.split(',').filter(url => url.trim() !== '')
  const index = imageUrls.findIndex(url => url === uploadFile.url)
  
  if (index > -1) {
    imageUrls.splice(index, 1)
    tableData.value.rabit_CheckImg = imageUrls.join(',')
    // 更新数据库
    saveImagesToDatabase()
    ElMessage.success('图片删除成功')
  }
}
//图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
</script>

<!-- 使用黑色实线边框,加号，边框 -->
<style>
.avatar-uploader .el-upload {
  border: 1px solid var(--el-border-color);
  border-color: black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 17px;
  color: black;
  width: 17px;
  height: 17px;
  text-align: center;
}

</style>